package controllers;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;

import play.data.validation.Required;
import models.DeviceModel;
import models.DeviceStatus;
import models.Operator;
import models.Oplog;
import models.Shop;
import models.Device;
import models.Standard;
import services.AuthorityService;
import services.DeviceModelService;
import services.HraDetailService;
import services.HraStandardService;
import services.DeviceService;
import services.ShopService;
import utils.BizConstants;
import utils.ExcelUtil;
import utils.FileConfig;
import utils.Validate;
import vos.DeviceVo;
import vos.HraDetailSearchVo;
import vos.HraDetailView;
import vos.HraStandardSearchVo;
import vos.ReturnCode;
import vos.ReturnListVo;
import vos.DeviceSearchVo;
import vos.ShopVo;

public class DeviceController extends BaseController {
	/**
	 * 设备列表页面
	 *
	 * @Title: deviceList 
	 * @return: void
	 */
	public static void deviceList(String menuid){
		Operator oper=getLoginUser();
		List<String> auths=AuthorityService.getAuthorityByOperAndMenu(menuid,oper.operatorid);
		for(String auth : auths){
			renderArgs.put(auth, auth);
		}
		render();
	}
	/**
	 * 获取设备列表
	 *
	 * @Title: getDevice 
	 * @return: void
	 */
	public static void getDevice(int page,int rows, String sort,String order,
			String deviceid,String devicename,String shopid,String shopname,Boolean isflag,
			String dealerid,String dealername,String modelid,String status){
		if(page==0){
			page=1;
		}
		if(rows==0){
			rows=BizConstants.pagesize;
		}
		DeviceSearchVo vo =new DeviceSearchVo(page,rows,order,sort,
				deviceid,devicename,shopid,shopname,isflag,dealerid,dealername,modelid,status);
		long total=DeviceService.countDevice(vo);
		ReturnListVo listVo=new ReturnListVo();
		listVo.setTotal(total);
		List<DeviceVo> lists=DeviceService.listDevice(vo);
		listVo.setRows(lists);
		renderJSON(listVo);
	}
	/**
	 * 批量启用
	 *
	 * @Title: betchEnable 
	 * @return: void
	 */
	public static void betchEnable(String ids){
		if(!checkAuthority("DEVICE_ENABLE")){
			renderFailedJson(ReturnCode.ErrorCode, "您没有操作权限，请联系管理员");
		}
		Operator oper=getLoginUser();
		if(StringUtils.isEmpty(ids)){
			renderFailedJson(ReturnCode.ErrorCode,"未选中记录");
		}
		String[] id=ids.split(",");
		List<String> listid=new ArrayList<String>();
		Collections.addAll(listid, id);
		for(String ss : listid){
			DeviceVo device=DeviceService.getViewById(ss);
			if(device==null){
				renderFailedJson(ReturnCode.ErrorCode,"设备不存在，编号为："+ss);
			}
			if(device.shopflag){
				renderFailedJson(ReturnCode.ErrorCode,"设备所属门店被停用，编号为："+ss);
			}
		}
		boolean issuccess=DeviceService.betchEnable(listid,oper.operatorid);
		if(issuccess){
			Oplog oplog=new Oplog(oper.operatorid,"批量启用设备"+ids,"设备管理");
			oplog.save(oplog);
			renderFailedJson(ReturnCode.SuccessCode,"启用成功");
		}
		else{
			renderFailedJson(ReturnCode.ErrorCode,"启用失败");
		}
	}
	/**
	 * 批量停用
	 *
	 * @Title: betchEnable 
	 * @return: void
	 */
	public static void betchDisable(String ids){
		if(!checkAuthority("DEVICE_DISABLE")){
			renderFailedJson(ReturnCode.ErrorCode, "您没有操作权限，请联系管理员");
		}
		Operator oper=getLoginUser();
		if(StringUtils.isEmpty(ids)){
			renderFailedJson(ReturnCode.ErrorCode,"未选中记录");
		}
		String[] id=ids.split(",");
		List<String> listid=new ArrayList<String>();
		Collections.addAll(listid, id);
		boolean issuccess=DeviceService.betchDisable(listid,oper.operatorid);
		if(issuccess){
			Oplog oplog=new Oplog(oper.operatorid,"批量停用设备"+ids,"设备管理");
			oplog.save(oplog);
			renderFailedJson(ReturnCode.SuccessCode,"停用成功");
		}
		else{
			renderFailedJson(ReturnCode.ErrorCode,"停用失败");
		}
	}
	/**
	 * 批量删除
	 *
	 * @Title: betchEnable 
	 * @return: void
	 */
	public static void betchDel(String ids){
		if(!checkAuthority("DEVICE_BETCHDEL")){
			renderFailedJson(ReturnCode.ErrorCode, "您没有操作权限，请联系管理员");
		}
		if(StringUtils.isEmpty(ids)){
			renderFailedJson(ReturnCode.ErrorCode,"未选中记录");
		}
		boolean issuccess=DeviceService.betchDel(ids);
		if(issuccess){
			Operator oper =getLoginUser();
			Oplog oplog=new Oplog(oper.operatorid,"批量删除设备"+ids,"设备管理");
			oplog.save(oplog);
			renderFailedJson(ReturnCode.SuccessCode,"删除成功");
		}
		else{
			renderFailedJson(ReturnCode.ErrorCode,"删除失败");
		}
	}
	/**
	 * 删除记录
	 *
	 * @Title: delDevice 
	 * @param id 设备id
	 * @return: void
	 */
	public static void delDevice(String id){
		if(!checkAuthority("DEVICE_DELETE")){
			renderFailedJson(ReturnCode.ErrorCode, "您没有操作权限，请联系管理员");
		}
		if(StringUtils.isEmpty(id)){
			renderFailedJson(ReturnCode.ErrorCode,"选中记录不能为空");
		}
		boolean issuccess=DeviceService.delDevice(id);
		if(issuccess){
			Operator oper =getLoginUser();
			Oplog oplog=new Oplog(oper.operatorid,"删除设备"+id,"设备管理");
			oplog.save(oplog);
			renderFailedJson(ReturnCode.SuccessCode,"删除成功");
		}
		else{
			renderFailedJson(ReturnCode.ErrorCode,"删除失败");
		}
	}
	/**
	 * 添加设备
	 *
	 * @Title: addDevice 
	 * @return: void
	 */
	public static void deviceAdd(){
		render();
	}
	/**
	 * 复制设备
	 *
	 * @Title: addDevice 
	 * @return: void
	 */
	public static void deviceCopy(String id){
		Device oldDevice=DeviceService.getById(id);
		renderArgs.put("device", oldDevice);
		render("DeviceController/deviceAdd.html");
	}
	/**
	 * 验证设备编号是否存在
	 *
	 * @Title: checkCode 
	 * @param deviceid 设备id
	 * @return: void
	 */
	public static void checkCode(String value){
//		if(!Validate.isEnglishNum(value)){
//			renderFailedJson(ReturnCode.ErrorCode, "设备编号格式不正确");
//		}
		if(StringUtils.isEmpty(value)){
			renderFailedJson(ReturnCode.ErrorCode, "编号不能为空");
		}
		boolean isexist=DeviceService.checkCode(value);
		if(isexist){
			renderFailedJson(ReturnCode.ErrorCode, "编号已存在");
		}
		else{
			renderFailedJson(ReturnCode.SuccessCode, "该编号可以使用");
		}
	}
	/**
	 * 保存设备信息
	 *
	 * @Title: saveDevice 
	 * @param device 设备对象
	 * @return: void
	 */
	public static void saveDevice(Device device){
		if(!checkAuthority("DEVICE_ADD")){
			renderFailedJson(ReturnCode.ErrorCode, "您没有操作权限，请联系管理员");
		}
		Operator oper=getLoginUser();
		if(device==null){
			renderFailedJson(ReturnCode.ErrorCode, "设备不能为空");
		}
		if(device.buildtime==null){
			renderFailedJson(ReturnCode.ErrorCode, "安装日期不能为空");
		}
		if(StringUtils.isEmpty(device.deviceid)){
			renderFailedJson(ReturnCode.ErrorCode, "编号不能为空");
		}
		if(StringUtils.isEmpty(device.devicename)){
			renderFailedJson(ReturnCode.ErrorCode, "名称不能为空");
		}
		if(device.deviceprice==null){
			renderFailedJson(ReturnCode.ErrorCode, "设备价格不能为空");
		}
		if(device.remark.length()>255){
			renderFailedJson(ReturnCode.ErrorCode, "备注长度不能大于255");
		}
		Device oldDevice=DeviceService.getById(device.deviceid);
		if(oldDevice!=null){
			renderFailedJson(ReturnCode.ErrorCode, "设备已存在");
		}
		ShopVo shop=ShopService.getById(device.shopid);
		if(shop==null){
			renderFailedJson(ReturnCode.ErrorCode, "门店不存在");
		}
		DeviceModel model=DeviceModelService.getById(device.devicemodel);
		if(model==null){
			renderFailedJson(ReturnCode.ErrorCode, "型号不存在");
		}
//		if(!Validate.isEnglishNum(device.deviceid)){
//			renderFailedJson(ReturnCode.ErrorCode, "设备编号格式不正确");
//		}
		//验证价格
		if(!Validate.isFloat(Double.toString(device.deviceprice))){
			renderFailedJson(ReturnCode.ErrorCode, "设备价格格式不正确");
		}
		device.createname=oper.operatorid;
		boolean isSuccess=DeviceService.saveDevice(device);
		if(isSuccess){
			Oplog oplog=new Oplog(oper.operatorid,"添加设备"+device.deviceid,"设备管理");
			oplog.save(oplog);
			renderFailedJson(ReturnCode.SuccessCode, "保存成功");
		}
		else{
			renderFailedJson(ReturnCode.ErrorCode, "保存失败");
		}
	}
	/**
	 * 编辑设备
	 *
	 * @Title: deviceEdit 
	 * @return: void
	 */
	public static void deviceEdit(String id){
		Device oldDevice=DeviceService.getById(id);
		renderArgs.put("device", oldDevice);
		render();
	}
	/**
	 * 保存设备信息
	 *
	 * @Title: saveDevice 
	 * @param device 设备对象
	 * @return: void
	 */
	public static void updateDevice(Device device){
		if(!checkAuthority("DEVICE_EDIT")){
			renderFailedJson(ReturnCode.ErrorCode, "您没有操作权限，请联系管理员");
		}
		Operator oper=getLoginUser();
		if(device==null){
			renderFailedJson(ReturnCode.ErrorCode, "设备不能为空");
		}
		if(StringUtils.isEmpty(device.deviceid)){
			renderFailedJson(ReturnCode.ErrorCode, "编号不能为空");
		}
		if(StringUtils.isEmpty(device.devicename)){
			renderFailedJson(ReturnCode.ErrorCode, "名称不能为空");
		}
		if(device.buildtime==null){
			renderFailedJson(ReturnCode.ErrorCode, "安装日期不能为空");
		}
		if(device.deviceprice==null){
			renderFailedJson(ReturnCode.ErrorCode, "设备价格不能为空");
		}
		if(device.remark.length()>255){
			renderFailedJson(ReturnCode.ErrorCode, "备注长度不能大于255");
		}
		if(StringUtils.isEmpty(device.shopid)){
			renderFailedJson(ReturnCode.ErrorCode, "门店不能为空");
		}
		if(StringUtils.isEmpty(device.shopid)){
			renderFailedJson(ReturnCode.ErrorCode, "门店不能为空");
		}
		ShopVo shop=ShopService.getById(device.shopid);
		if(shop==null){
			renderFailedJson(ReturnCode.ErrorCode, "门店不存在");
		}
		DeviceModel model=DeviceModelService.getById(device.devicemodel);
		if(model==null){
			renderFailedJson(ReturnCode.ErrorCode, "型号不存在");
		}
		//验证价格
		if(!Validate.isFloat(Double.toString(device.deviceprice))){
			renderFailedJson(ReturnCode.ErrorCode, "设备价格格式不正确");
		}
		device.modifyname=oper.operatorid;
		boolean isSuccess=DeviceService.updateDevice(device);
		if(isSuccess){
			Oplog oplog=new Oplog(oper.operatorid,"编辑设备"+device.deviceid,"设备管理");
			oplog.save(oplog);
			renderFailedJson(ReturnCode.SuccessCode, "保存成功");
		}
		else{
			renderFailedJson(ReturnCode.ErrorCode, "保存失败");
		}
	}
	/**
	 * 查看设备
	 *
	 * @Title: shopEdit 
	 * @return: void
	 */
	public static void deviceView(String id){
		if(!checkAuthority("DEVICE_VIEW")){
			renderFailedJson(ReturnCode.ErrorCode, "您没有操作权限，请联系管理员");
		}
		if(StringUtils.isEmpty(id)){
			renderFailedJson(ReturnCode.ErrorCode, "id不能为空");
		}
		DeviceVo device=DeviceService.getViewById(id);
		renderArgs.put("device", device);
		render();
	}
	/**
	 * 获取设备健康状态
	 *
	 * @Title: getStatus 
	 * @return: void
	 */
	public static void getStatus(){
		List<DeviceStatus> status=DeviceService.getStatus();
		List<Map<String,String>> combos=new ArrayList<Map<String,String>>();
		for(DeviceStatus statu : status){
			Map<String,String> map=new HashMap<String,String>();
			map.put("id", statu.statusid);
			map.put("text", statu.statusname);
			combos.add(map);
		}
		renderJSON(combos);
	}
	/**
	 * 根据设备获取HRA体检数据
	 *
	 * @Title: getHRA 
	 * @param page
	 * @param rows
	 * @param sort
	 * @param order
	 * @return: void
	 */
	public static void getHRA(int page,int rows, String sort,String order,String deviceid){
		if(page==0){
			page=1;
		}
		if(rows==0){
			rows=BizConstants.pagesize;
		}
		HraDetailSearchVo vo =new HraDetailSearchVo(page,rows,order,sort,deviceid);
		long total=HraDetailService.countByDevice(vo);
		ReturnListVo listVo=new ReturnListVo();
		listVo.setTotal(total);
		List<HraDetailView> lists=HraDetailService.listByDevice(vo);
		listVo.setRows(lists);
		renderJSON(listVo);
	}
	
	/**
	 * 导出为excel
	 *
	 * @Title: exportXls 
	 * @param deviceid
	 * @param devicename
	 * @param shopid
	 * @param shopname
	 * @param isflag
	 * @param dealerid
	 * @param dealername
	 * @param modelid
	 * @param status
	 * @return: void
	 */
	public static void exportXls(String deviceid,String devicename,String shopid,String shopname,Boolean isflag,
			String dealerid,String dealername,String modelid,String status){
		if(!checkAuthority("DEVICE_EXPORT")){
			renderFailedJson(ReturnCode.ErrorCode, "您没有操作权限，请联系管理员");
		}
		DeviceSearchVo vo =new DeviceSearchVo(deviceid,devicename,shopid,shopname,isflag,dealerid,dealername,modelid,status);
		List<DeviceVo> lists=DeviceService.exportXls(vo);
		long y=System.currentTimeMillis();
		String fileName = "设备信息"+y+".csv";
        response.contentType = "application/x-download";
        Operator oper=getLoginUser();
        Oplog oplog=new Oplog(oper.operatorid,"导出设备信息数据","设备管理");
		oplog.save(oplog);
        renderBinary(ExcelUtil.buildExportFile(FileConfig.deviceXlsTemplate, lists), fileName);
	}
	/**
	 * 获取下拉列表
	 *
	 * @Title: getCombobox 
	 * @return: void
	 */
	public static void getCombobox(){
		List<Device> devices=DeviceService.getCombobox();
		List<Map<String,String>> combos=new ArrayList<Map<String,String>>();
		for(Device device :devices){
			Map<String,String> map=new HashMap<String,String>();
			map.put("id", device.deviceid);
			map.put("text", device.devicename);
			combos.add(map);
		}
		renderJSON(combos);
	}
}
